package com.ruoyi.platform.system.verify.servise;

import com.google.code.kaptcha.Producer;
import com.ruoyi.base.redis.login.PwdWrongTimesRedis;
import com.ruoyi.base.redis.verifycode.VerifyCodeRedis;
import com.ruoyi.base.service.BaseService;
import com.ruoyi.base.utils.uuid.UuidUtils;
import com.ruoyi.platform.system.verify.pojo.VerifyCodeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Base64;

/**
 * 验证码
 *
 * @author lcf
 */
@Service
public class VerifyCodeService extends BaseService {
    @Autowired
    private VerifyCodeRedis verifyCodeRedis;

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Autowired
    private PwdWrongTimesRedis pwdWrongTimesRedis;

    /**
     * 获取验证码
     */
    public VerifyCodeDTO getVerifyCode() {
        if (!pwdWrongTimesRedis.isNeedVerifyCode()) {
            return new VerifyCodeDTO(false);
        }

        String key = UuidUtils.getUuid();
        String code = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(code);

        verifyCodeRedis.cache(key, code);
        try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
            // 转换流信息写出
            ImageIO.write(image, "jpg", os);
            return new VerifyCodeDTO(key, Base64.getEncoder().encodeToString(os.toByteArray()), true);
        } catch (Exception e) {
            throw exception(e.getMessage(), e);
        }
    }
}
